<?php
/**
 *UserServices
 * @author tan bing
 * @date 2021-08-11 12:35
 */


namespace Modules\User\Services\Api;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Share\Entities\ShareUser;
use Modules\Share\Entities\ShareUserParent;
use Modules\User\Entities\Favorite;
use Modules\User\Entities\BaseModel;
use App\User;
use Modules\User\Repositories\Contracts\UserInterface;
use Nwidart\Modules\Facades\Module;

class UserServices extends BaseService
{

    /**
     * @var Request
     * @author tan bing
     */
    private $request;

    private UserInterface $userInterface;

    /**
     * UserServices constructor.
     *
     * @param Request $request
     * @author tan bing
     * @date 2021-08-11 12:36
     */
    public function __construct(Request $request, UserInterface $userInterface)
    {
        $this->request = $request;
        $this->userInterface = $userInterface;
    }

    /**
     * @return mixed|null
     * @author tan bing
     * @date 2021-08-11 12:36
     */
    public function info()
    {
        $userId = $this->request->attributes->get('userId');
        $user = User::find($userId);
        $parentUser = User::find($user->parent_id_1);
        $user->parent = $parentUser ? $parentUser->nickname : '总店';

        return $user;
    }

    /**
     * 收藏列表
     */
    public function getFavoriteList()
    {
        $page = intval($this->request->input('page',1));
        $limit = intval($this->request->input('limit',10));
        $user_id = $this->request->attributes->get('userId');
        
        $where = [
            ['favorite.user_id','=',$user_id],
            ['favorite.is_delete','=',0],
        ];
        //获取总条数
        $count = Favorite::where($where)->count();
        //求偏移量
        $offset = ($page-1)*$limit;

        $list = Favorite::where($where)
            ->leftJoin('goods', 'goods.id', '=', 'favorite.goods_id')
            ->select('favorite.*','goods.name','goods.pic as goods_pic','goods.price')
            ->offset($offset)->limit($limit)
            ->get();
        foreach($list as $key => $v){
            $domain = BaseModel::getDomain();
            $list[$key]['goods_pic'] = $domain.'/'.$v['goods_pic'];
        }
        return  compact('count','list');
    }

    /**
     * @return mixed
     * @throws \Throwable
     * @author tan bing
     * @date 2021-11-09 17:38
     */
    public function bindParentId()
    {
        $parentId = $this->request->post('parent_id');
        $userId = $this->request->attributes->get('userId');
        try {
            DB::beginTransaction();
            $user = User::find($userId);
            if(!empty($user->parent_id_1)) throw new \Exception('已经绑定父级，不能重复绑定');
            $user->parent_id_1 = $parentId;
            $this->check($userId, $parentId);
            if(!$user->save()) throw new \Exception('绑定失败');
            $res = $this->userInterface->addShareUserRelation($userId, $parentId);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }

        return $res;
    }

    /**
     * @param $userId
     * @param $parentId
     * @throws \Exception
     * @author tan bing
     * @date 2021-11-09 17:28
     */
    public function check($userId, $parentId)
    {
        if(!Module::has('Share')) throw new \Exception('分销模块未安装，绑定失败');
        if(empty($parentId)) throw new \Exception('父级ID不能为空');
        $parentUser = User::find($parentId);
        if(!$parentUser || !$parentUser->is_distributor) throw new \Exception('父级不是分销用户，绑定失败');
        $shareUser = ShareUser::query()->where('user_id', $userId)->first();
        if(!$shareUser) throw new \Exception('父级分销商用户不存在或已删除，绑定失败');
    }
}